import XLSX, { CellObject, WSKeys } from "xlsx";
import _ from "lodash";
import { config as o } from "./config";
import dayjs from "dayjs";

const orgin = XLSX.readFile(`./xlsx/${o.xlsxName}.xlsx`);
let sheet = orgin.Sheets[o.sheetName];
let range = XLSX.utils.decode_range(sheet["!ref"]!);
let json_arr: any = [];

function main() {
  for (let R = o.startRow; R <= range.e.r; ++R) {
    let row_arr: any = {};
    for (let C = o.startColmn; C <= range.e.c; ++C) {
      let index = o.selectColmn.findIndex((k: any) => k.col === C);
      if (index != -1) {
        let cell_address = { c: C, r: R };
        let cell = XLSX.utils.encode_cell(cell_address);
        if (sheet[cell]?.v) {
          row_arr[o.selectColmn[index].des] = handleField(
            sheet[cell],
            o.selectColmn[index].key
          );
        }
      }
    }
    row_arr["优先级"] = "中";
    row_arr["迭代"] = o.iteration;

    json_arr.push(row_arr);
  }
  json_arr = json_arr.filter((k: any) => {
    if (k["标题"] && k["负责人"] == o.filterCharge) return true;
  });
  json_arr.map((k: any) => {
    if (k["模块"]) {
      k["标题"] = `${k["模块"]}-${k["标题"]}`;
      delete k["模块"];
    }
  });

  console.log(json_arr);
  writeTo();
}
interface JsonArr {}
type KeyEnum =
  | "module"
  | "title"
  | "describe"
  | "charge"
  | "status"
  | "startTime"
  | "endTime"
  | "useTime";

const handleField = (val: CellObject | WSKeys | any, key: KeyEnum) => {
  if (key == "startTime" || key == "endTime") {
    return dayjs(val.w).format("YYYY-MM-DD");
  } else if (key == "charge") {
    return val.v.split("@")[1];
  } else if (key == "status") {
    return "待处理";
  } else if (key == "describe") {
    if (val.v) {
      return val.v;
    }
  } else {
    return val.v;
  }
};

const writeTo = () => {
  let jsonWorkSheet = XLSX.utils.json_to_sheet(json_arr);
  let workBook = {
    SheetNames: ["jsonWorkSheet"],
    Sheets: {
      jsonWorkSheet: jsonWorkSheet,
    },
  };
  XLSX.writeFile(workBook, "./xlsx/result.xlsx");
  console.log("写入成功");
};

main();
